<template>
  <view class="container">
    <view class="image-item" v-for="(item, i) in imageList" :key="i">
      <image class="image-box" @click="preview(item)" mode="aspectFill" :src="item"></image>
      <view class="image-delete-box" @click="deleteImage(i)">
        <uni-icons type="closeempty" size="17" color="white"></uni-icons>
      </view>
    </view>
    <view class="image-add-box" v-if="imageList.length < 9" @click="chooseImage">
      <view class="image-add-item">
        <text class="image-add-item-text">+</text>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    name: "my-upload-image",
    data() {
      return {
        // 用户选择的图片列表
        imageList: [],
      };
    },
    methods: {
      //选择图片
      chooseImage() {
        uni.chooseImage({
          count: 9 - this.imageList.length,
          success: (res) => {
            this.imageList = [...this.imageList, ...res.tempFilePaths]
            this.$emit('updateImage', this.imageList)
          }
        })
      },
      // 预览图片
      preview(url) {
        uni.previewImage({
          urls: this.imageList,
          current: url
        })
      },
      // 删除图片
      deleteImage(index) {
        this.imageList.splice(index, 1)
        this.$emit('updateImage', this.imageList)
      }
    },
  }
</script>

<style lang="scss">
  .container {
    display: flex;
    flex-wrap: wrap;

    .image-item {
      position: relative;
      width: 210rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 10rpx;

      .image-box {
        width: 200rpx;
        height: 200rpx;
        background: whitesmoke;
      }

      .image-delete-box {
        position: absolute;
        top: 5rpx;
        right: 0;
        height: 60rpx;
        width: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.5);
      }
    }

    .image-add-box {
      width: 210rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 10rpx;

      .image-add-item {
        width: 200rpx;
        height: 200rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #eee;

        .image-add-item-text {
          font-size: 120rpx;
          font-weight: 100;
          color: grey;
        }
      }
    }
  }
</style>